package leetcode.weekly.week322;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

//Solution3Test
public class Solution3 {

	int ans;
	Set<Integer> been;

	public int minScore(int n, int[][] roads) {
		ans = Integer.MAX_VALUE;
		int arraySize = n + 1;
		been = new HashSet<>();
		List<Integer>[] nexts = new ArrayList[arraySize];
		for (int i = 0; i < arraySize; i++) {
			nexts[i] = new ArrayList<>();
		}
		Map<Integer, Map<Integer, Integer>> dis = new HashMap<>();
		for (int i = 0; i < roads.length; i++) {
			int[] r = roads[i];
			int a = r[0], b = r[1], d = r[2];
			nexts[a].add(b);
			nexts[b].add(a);
			dis.computeIfAbsent(a, key -> new HashMap<>()).put(b, d);
			dis.computeIfAbsent(b, key -> new HashMap<>()).put(a, d);
		}
		f(1, nexts, dis);
		return ans;
	}

	private void f(int i, List<Integer>[] nexts, Map<Integer, Map<Integer, Integer>> dis) {
		List<Integer> next = nexts[i];
		for (int n : next) {
			ans = Math.min(ans, dis.get(i).get(n));
			if (!been.contains(n)) {
				been.add(n);
				f(n, nexts, dis);
			}
		}
	}

}
